<script lang="js" setup name="SeriesItem">
import { ref, reactive, computed, onMounted } from "vue";
import { desensitizeSubstring, IsPhone, IsPC } from "../utils";
import { useAppStore } from "../stores/appStore";

const emit = defineEmits(["selected", "dblclick"]);
const appStore = useAppStore();
const IsSel = ref(false);
const imgSrc = ref(null);

// 响应式变量用于跟踪拖拽状态
const isDragging = ref(false);
const dragStartPos = reactive({ x: 0, y: 0 });

const props = defineProps({
    series: {
        type: Object,
        required: true
    },
    pos: {
        type: Number,
        required: true,
    },
});

const thumbId = computed(() => {
    return "thumb-" + props.series.seriesInsUid;
});

const seriesTitle = computed(() => {
    let patName = props.series.study.patientName;
    if (config.desensitize) {
        patName = desensitizeSubstring(patName, 1, -1);
    }
    return (
        props.series.study.modality +
        " - " +
        props.series.seriesNumber +
        " " +
        patName
    );
});

const thumbClass = computed(() => {
    let ss = IsPhone()
        ? "thumbnail-phone"
        : appStore.navbarPos === "left"
        ? "thumbnail"
        : "thumbnail-phone";
    let s = "unselect";
    if (IsSel.value) {
        s = "selected";
    }

    // 添加拖拽状态样式
    if (isDragging.value) {
        s += " dragging";
    }

    return ss + " " + s;
});

const tipPlacement = computed(() => {
    return appStore.navbarPos === "left" ? "right" : "top";
});

const showTooltip = computed(() => {
    return IsPhone();
});

const canDrag = computed(() => {
    return true;
});

const dragEnter = (e, data) => {
    e.dataTransfer.setData("seriesInsUid", data);
};


const dragEnd = (e) => {
    e.dataTransfer.clearData();
    isDragging.value = false;
};

// === 移动端触摸事件优化 ===
const touchStart = (e) => {
    // 阻止默认行为，防止页面滚动
    e.preventDefault();

    const touch = e.touches[0];
    dragStartPos.x = touch.clientX;
    dragStartPos.y = touch.clientY;
    isDragging.value = false;

    // 记录触摸开始时间用于点击判断
    e.currentTarget._touchStartTime = Date.now();
};

const touchMove = (e) => {
    if (e.touches.length === 0) return;

    const touch = e.touches[0];
    const deltaX = Math.abs(touch.clientX - dragStartPos.x);
    const deltaY = Math.abs(touch.clientY - dragStartPos.y);

    // 移动超过阈值视为拖拽
    if (deltaX > 15 || deltaY > 15) {
        isDragging.value = true;
        e.preventDefault();

        // 添加拖拽视觉反馈
        const el = e.currentTarget;
        el.style.opacity = "0.7";
        el.style.transform = "scale(0.95)";
        el.style.transition = "all 0.15s ease";

        // 显示拖拽提示
        if (!document.querySelector('.drag-hint')) {
            showDragHint();
        }
    }
};

const showDragHint = () => {
    const hint = document.createElement('div');
    hint.className = 'drag-hint';
    hint.innerHTML = `
        <div style="text-align: center; padding: 15px; background: rgba(0,0,0,0.8); border-radius: 12px; color: white; font-size: 16px;">
            <div style="margin-bottom: 10px;">拖拽到显示区域</div>
            <div style="font-size: 12px; color: #ccc;">释放以加载序列</div>
        </div>
    `;
    hint.style.position = 'fixed';
    hint.style.left = '50%';
    hint.style.top = '50%';
    hint.style.transform = 'translate(-50%, -50%)';
    hint.style.zIndex = '99999';
    document.body.appendChild(hint);
};

const removeDragHint = () => {
    const hint = document.querySelector('.drag-hint');
    if (hint) {
        document.body.removeChild(hint);
    }
};

const touchEnd = (e) => {
    const el = e.currentTarget;

    // 恢复样式
    el.style.opacity = "";
    el.style.transform = "";
    el.style.transition = "";

    // 移除拖拽提示
    removeDragHint();

    // 处理点击和拖拽结束
    if (isDragging.value) {
        handleDrop(e);
        isDragging.value = false;
    } else {
        // 点击处理（短触摸）
        const touchDuration = Date.now() - el._touchStartTime;

        // 短触摸视为点击（小于300ms）
        if (touchDuration < 300) {
            handleClick(e);
        }
    }
};

const handleDrop = (e) => {
    const touch = e.changedTouches[0];
    const displayers = document.querySelectorAll('.displaybox');
    let targetDisplayer = null;

    for (const displayer of displayers) {
        const rect = displayer.getBoundingClientRect();
        if (
            touch.clientX >= rect.left &&
            touch.clientX <= rect.right &&
            touch.clientY >= rect.top &&
            touch.clientY <= rect.bottom
        ) {
            targetDisplayer = displayer;
            break;
        }
    }

    if (targetDisplayer) {
        const seriesInsUid = props.series.seriesInsUid;

        // 触发全局拖放事件
        const dropEvent = new CustomEvent('seriesDrop', {
            detail: { seriesInsUid }
        });
        window.dispatchEvent(dropEvent);
    }
};

const handleClick = (e) => {
    // 阻止事件冒泡，避免多次触发
    e.stopPropagation();

    // 触发选中事件
    emit("selected", { pos: props.pos });
};

const onDblClick = (e) => {
    emit("dblclick", { pos: props.pos });
};

const showMenu = (e) => {
    // 右键菜单逻辑
};

const setSelected = (bSel) => {
    IsSel.value = bSel;
};

defineExpose({
    setSelected,
});

onMounted(() => {
    props.series.GetThumb().then((png) => {
        imgSrc.value = new URL(png, import.meta.url).href;
    });
});
</script>

<template>
	<div
		:class="thumbClass"
		:draggable="canDrag"
		:id="thumbId"
		@dragstart="dragEnter($event, series.seriesInsUid)"
		@dragend="dragEnd"
		@click="handleClick"
		@dblclick="onDblClick"
		@contextmenu.prevent="showMenu"
		@touchstart="touchStart"
		@touchmove="touchMove"
		@touchend="touchEnd"
		@touchcancel="touchEnd"
	>
		<h3 class="thumb-title">{{ seriesTitle }}</h3>
		<div class="img-container">
			<img class="img-contain" :src="imgSrc" alt="" draggable="false" />
		</div>
		<p class="imgcnt">{{ series.GetCount() }}</p>
		<progress ref="pg" value="0" max="1"></progress>
	</div>
</template>

<style lang="scss" scoped>
.thumbnail,
.thumbnail-phone {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	position: relative;
	background-color: var(--color-study-bg);
	border-radius: 4px;
	border-top: 1px solid var(--color-border-lt);
	border-left: 1px solid var(--color-border-lt);
	border-right: 2px groove var(--color-border-rb);
	border-bottom: 2px groove var(--color-border-rb);
	flex-shrink: 0;
	cursor: pointer;
	touch-action: manipulation;
	-webkit-tap-highlight-color: transparent;
	user-select: none;
	transition: all 0.2s ease;

	&.dragging {
		opacity: 0.7 !important;
		transform: scale(0.95) !important;
		box-shadow: 0 0 15px rgba(52, 152, 219, 0.6);
	}
}

.thumbnail {
	width: 100%;
	aspect-ratio: 4/3;
}

.thumbnail-phone {
	height: 100%;
	min-width: 150px;
	max-width: 150px; /* 使用固定宽度而不是百分比，防止撑大容器 */
	flex-shrink: 0;
}

.thumb-title {
	height: 2rem;
	font-weight: normal;
	font-size: 1.4rem;
	margin: 0;
	padding: 0 5px;
	text-align: center;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 100%;
}

progress {
	width: 98%;
	height: 0.4rem;
	background-color: lightskyblue;
	margin-top: 1px;
	margin-bottom: 1px;
	left: 1%;
	border-radius: 2px;
	flex-shrink: 0;
}

/* 进度条样式保持不变 */

p.imgcnt {
	position: absolute;
	color: #12e08a;
	font-size: 1.25rem;
	pointer-events: none;
	z-index: 1;
	right: 0.6rem;
	bottom: 0.6rem;
}

.img-container {
	display: flex;
	background-color: black;
	width: 100%;
	height: 7.5rem;
	align-items: center;
	justify-content: center;
	flex: 1;
	pointer-events: none;
}

img {
	width: auto;
	height: 90%;
	pointer-events: none;
}

.selected {
	background-color: var(--color-study-active);
	color: var(--color-selected-text);
	border: 2px solid #3498db;
}

.unselect {
	background-color: var(--color-study-bg);
	color: var(--color-unselect-text);
}
</style>
